<template>
  <div class="all-screen position-relative" ref="register">
    <div ref="rainBg" class="rain-container"></div>
    <div class="login-container">
      <h5 class="login-title">登录</h5>
      <el-form :model="user" ref="loginForm">
        <el-form-item prop="username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
          <h6 class="login-item-title">用户名</h6>
          <el-input v-model="user.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]" >
          <h6 class="login-item-title">密码</h6>
          <el-input v-model="user.password" placeholder="请输入密码"
            @keyup.enter.native="login('loginForm')"></el-input>
        </el-form-item>
      </el-form>
        <el-button type="primary" class="w-100" @click="login('loginForm')"
          style="letter-spacing: 16px;">登录</el-button>
        <router-link to="/register" class="mt-3 float-right">尚未注册,去注册 >>></router-link>
    </div>
  </div>
</template>
<script>
import api from '@/api'
import { mapState } from 'vuex';
import TextRain from '../register/rain'

export default {
  title: "个人登录",
  data() {
    return {
      user: {
        username: "",
        password: ""
      }
    }
  },
  created() {
    // if (this.token) {
    //   this.$router.push({name: 'manager'})
    // }
  },
  mounted() {
    TextRain(this.$refs.rainBg)
    const username = localStorage.getItem('username')
    const password = localStorage.getItem('password')
    this.user.username = username
    this.user.password = password
  },
  methods: {
    login(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const { username, password } = this.user
          this.$get(`${api.login}?username=${username}&password=${password}`).then(res => {
            localStorage.setItem("username", username)
            localStorage.setItem("password", password)
            this.$store.commit('user/set', res.data.data)
            this.$router.push({name: 'manager'})
          })
        }
      });
    },
  },
  computed: {
    ...mapState({
      token: (state)=> state['user'].token,
    }),
  }
}
</script>
<style lang="scss" scoped>
 .login-container {
    position: absolute;
    height: 400px;
    width: 500px;
    top: calc(50% - 300px);
    left: calc(50% - 250px);
    padding: 32px 64px;
    color: #000;
    border-radius: 5px;
    overflow: hidden;
    background: rgba(255, 255, 255, .8);
    box-shadow: 3px 3px 6px 3px rgba(0, 0, 0, .6);
    .login-title {
      font-size: 36px;
      color: #20A0FF;
      letter-spacing: 50px;
      text-align: center;
      margin-left: 60px;
    }
  }
</style>